import 'package:dio/dio.dart';

class HttpUtils {

  static final HttpUtils _instance = HttpUtils._internal();

  Dio dio;
  BaseOptions options;

  HttpUtils._internal(){
    if (dio == null) {
      options = BaseOptions(
          baseUrl: "",
          connectTimeout: 15000,
          receiveTimeout: 3000,
          headers: {}
      );
      dio = Dio(options);

    }
  }

  factory HttpUtils() => _instance;

  Future<Map<String, dynamic>> get(String url, {data, options, cancelToken}) async {
    Response response;
    try {
      response = await dio.get(url, queryParameters: data,
          options: options,
          cancelToken: cancelToken);
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消!' + e.message);
      } else {
        print('get请求发生错误' + e.message);
      }
    }
    return response.data;
  }

  Future<Map<String, dynamic>> post(String url, {data, options, cancelToken}) async {
    Response response;
    try {
      response = await dio.post(url, data: data,
          options: options,
          cancelToken: cancelToken);
    } on DioError catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消!' + e.message);
      } else {
        print('get请求发生错误' + e.message);
      }
    }
    return response.data;
  }

}